package com.cy.dda.comm.config;

import com.cy.dda.comm.properties.MongodbPoolProperties;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: mongodb
 * @author: Ocean
 * @create: 2018-06-09 09:53
 **/
@Configuration
@Slf4j
public class MongoConfig {

    // 注入配置实体
    @Autowired
    private MongodbPoolProperties mongodbPoolProperties;

    @Bean
    public MongoDbFactory mongoDbFactory() {
        //客户端配置（连接数、副本集群验证）
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(mongodbPoolProperties.getConnectionsPerHost());
        builder.minConnectionsPerHost(mongodbPoolProperties.getMinConnectionsPerHost());
        if (mongodbPoolProperties.getReplicaSet() != null) {
            builder.requiredReplicaSetName(mongodbPoolProperties.getReplicaSet());
        }
        MongoClientOptions mongoClientOptions = builder.build();

        // MongoDB地址列表
        List<ServerAddress> serverAddresses = new ArrayList<>();
        for (String host : mongodbPoolProperties.getHosts()) {
            Integer index = mongodbPoolProperties.getHosts().indexOf(host);
            Integer port = mongodbPoolProperties.getPorts().get(index);

            ServerAddress serverAddress = new ServerAddress(host, port);
            serverAddresses.add(serverAddress);
        }
        log.info("mongodb服务器地址:[{}]", serverAddresses.toString());

        // 连接认证
        List<MongoCredential> mongoCredentialList = new ArrayList<>();
        if (mongodbPoolProperties.getUsername() != null) {
            mongoCredentialList.add(MongoCredential.createScramSha1Credential(
                    mongodbPoolProperties.getUsername(),
                    mongodbPoolProperties.getAuthenticationDatabase() != null ? mongodbPoolProperties.getAuthenticationDatabase() : mongodbPoolProperties.getDatabase(),
                    mongodbPoolProperties.getPassword().toCharArray()));
        }
        log.info("mongodb连接信息:[{}]", mongoCredentialList.toString());

        //创建客户端和Factory
        MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredentialList, mongoClientOptions);
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, mongodbPoolProperties.getDatabase());

        return mongoDbFactory;
    }

}
